package com.open.capacity.finance.util;


import com.itextpdf.text.*;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.open.capacity.finance.entity.Pz;
import com.open.capacity.finance.entity.Pzfl;
import com.open.capacity.utils.BigDecimalUtil;
import com.open.capacity.utils.DateUtil;
import com.open.capacity.utils.StringUtil;

import java.util.List;

public class PdfPz {
    // 定义全局的字体静态变量
    private static Font titlefont;
    private static Font headfont;
    private static Font keyfont;
    private static Font textfont;
    private static Font text1font;
    private static Font text2font;
    private static Font text3font;
    private static Font text4font;
    private static Font text5font;
    private static Font text6font;
    private static Font totalfont;

    private static BaseFont bfChinese;
    // 最大宽度
    private static int maxWidth = 520;

    // 静态代码块
    static {
        try {
            // 不同字体（这里定义为同一种字体：包含不同字号、不同style）
            bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
            titlefont = new Font(bfChinese, 18, Font.NORMAL);
            headfont = new Font(bfChinese, 10, Font.NORMAL);
            keyfont = new Font(bfChinese, 10, Font.NORMAL);
            textfont = new Font(bfChinese, 10, Font.NORMAL);
            text1font = new Font(bfChinese, 9, Font.NORMAL);
            text2font = new Font(bfChinese, 8, Font.NORMAL);
            text3font = new Font(bfChinese, 7, Font.NORMAL);
            text4font = new Font(bfChinese, 6, Font.NORMAL);
            text5font = new Font(bfChinese, 5, Font.NORMAL);
            text6font = new Font(bfChinese, 4, Font.NORMAL);

            totalfont = new Font(bfChinese, 13, Font.NORMAL);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    // 生成PDF文件
    public void generatePDF(Document document, List<Pz> data, String[] headNames, float colWidths[]) throws Exception {
        int page = 1;
        // 内容
        if (data != null && data.size() > 0) {
            for (Pz item : data) {
                //页码
                Paragraph paragraphPage = new Paragraph("第" + page++ + "页", keyfont);
                paragraphPage.setAlignment(2); //设置文字居中 0靠左   1，居中     2，靠右
                paragraphPage.setIndentationLeft(0); //设置左缩进
                paragraphPage.setIndentationRight(8); //设置右缩进
                paragraphPage.setLeading(0f); //行间距
                paragraphPage.setSpacingBefore(60f); //设置段落上空白
                paragraphPage.setSpacingAfter(0f); //设置段落下空白
                document.add(paragraphPage);

                // 记账凭证
                Paragraph paragraphTitle = new Paragraph("记账凭证", titlefont);
                paragraphTitle.setAlignment(1); //设置文字居中 0靠左   1，居中     2，靠右
                paragraphTitle.setIndentationLeft(12); //设置左缩进
                paragraphTitle.setIndentationRight(12); //设置右缩进
                paragraphTitle.setLeading(20f); //行间距
                paragraphTitle.setSpacingBefore(60f); //设置段落上空白
                paragraphTitle.setSpacingAfter(15f); //设置段落下空白
                document.add(paragraphTitle);

                String pzrq = DateUtil.formatDate(item.getPzrq());
                // 日期

                PdfPTable firsttitle = new PdfPTable(3);
                firsttitle.setTotalWidth(PageSize.A4.getWidth() - 68);
                firsttitle.setWidths(new int[]{30, 40, 30});
                firsttitle.setLockedWidth(true);
                firsttitle.getDefaultCell().setFixedHeight(-10);
                firsttitle.getDefaultCell().setBorder(Rectangle.NO_BORDER);
                firsttitle.addCell(new Paragraph("", iTextPDFUtil.getColorFont(BaseColor.BLACK, 10, "宋体")));
                firsttitle.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
                firsttitle.addCell(new Paragraph(pzrq.substring(0, 4) + "年" + pzrq.substring(5, 7) + "月" + pzrq.substring(8, 10) + "日", iTextPDFUtil.getColorFont(BaseColor.BLACK, 10, "宋体")));
                firsttitle.getDefaultCell().setHorizontalAlignment(Element.ALIGN_RIGHT);

                int length = item.getPzflList().size();
                int total = length / 14 + ((length % 14) > 0 ? 1 : 0);

                firsttitle.addCell(new Paragraph("第1页，共" + total + "页", iTextPDFUtil.getColorFont(BaseColor.BLACK, 10, "宋体")));
                firsttitle.setSpacingAfter(20f); //设置段落下空白
                document.add(firsttitle);


                PdfPTable subtitle = new PdfPTable(3);
                subtitle.setTotalWidth(PageSize.A4.getWidth() - 68);
                subtitle.setWidths(new int[]{60, 20, 20});
                subtitle.setLockedWidth(true);
                subtitle.getDefaultCell().setFixedHeight(-10);
                subtitle.getDefaultCell().setBorder(Rectangle.NO_BORDER);
                subtitle.addCell(new Paragraph("账套：" + item.getZtName(), iTextPDFUtil.getColorFont(BaseColor.BLACK, 10, "宋体")));
                subtitle.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
                subtitle.addCell(new Paragraph("凭证号：(" + item.getPzz() + ")" + item.getPzh(), iTextPDFUtil.getColorFont(BaseColor.BLACK, 10, "宋体")));
                subtitle.getDefaultCell().setHorizontalAlignment(Element.ALIGN_RIGHT);
                subtitle.addCell(new Paragraph("附件：" + item.getFj(), iTextPDFUtil.getColorFont(BaseColor.BLACK, 10, "宋体")));
                document.add(subtitle);

                PdfPTable table2 = createTable(colWidths);
                table2.setSpacingBefore(8f);//表格前间距
                for (String col : headNames) {
                    table2.addCell(createCellNoHeight(col, headfont, Element.ALIGN_CENTER));
                }
                int index = 0;
                int count = 1;
                for (Pzfl rowData : item.getPzflList()) {
                    if (index >= 14) { //新的一页
                        document.add(table2);
                        //底部合计
                        PdfPTable table3 = new PdfPTable(new float[]{500, 80, 80});
                        table3.setTotalWidth(maxWidth);
                        table3.setLockedWidth(true);
                        table3.setHorizontalAlignment(Element.ALIGN_CENTER);
                        table3.getDefaultCell().setBorder(1);

                        table3.addCell(createCell("合计：人民币" + item.getTotal1(), totalfont));
                        table3.addCell(createCell(BigDecimalUtil.getData(item.getTotal2()).toString(), textfont));
                        table3.addCell(createCell(BigDecimalUtil.getData(item.getTotal2()).toString(), textfont));

                        document.add(table3);

                        PdfPTable footertitle = new PdfPTable(4);
                        footertitle.setTotalWidth(PageSize.A4.getWidth() - 68);
                        footertitle.setWidths(new int[]{33, 33, 33, 33});
                        footertitle.setLockedWidth(true);
                        footertitle.getDefaultCell().setFixedHeight(-10);
                        footertitle.getDefaultCell().setBorder(Rectangle.NO_BORDER);
                        footertitle.addCell(new Paragraph("财务主管：" + item.getCwzg(), iTextPDFUtil.getColorFont(BaseColor.BLACK, 10, "宋体")));
                        footertitle.addCell(new Paragraph("审核员：" + item.getShy(), iTextPDFUtil.getColorFont(BaseColor.BLACK, 10, "宋体")));
                        footertitle.addCell(new Paragraph("记账员：" + item.getJzy(), iTextPDFUtil.getColorFont(BaseColor.BLACK, 10, "宋体")));
                        footertitle.getDefaultCell().setHorizontalAlignment(Element.ALIGN_RIGHT);
                        footertitle.addCell(new Paragraph("制单员：" + item.getZdy(), iTextPDFUtil.getColorFont(BaseColor.BLACK, 10, "宋体")));
                        document.add(footertitle);
                        document.newPage();
                        table2 = createTable(colWidths);

                        //页码
                        paragraphPage = new Paragraph("第" + page++ + "页", keyfont);
                        paragraphPage.setAlignment(2); //设置文字居中 0靠左   1，居中     2，靠右
                        paragraphPage.setIndentationLeft(0); //设置左缩进
                        paragraphPage.setIndentationRight(16); //设置右缩进
                        paragraphPage.setLeading(0f); //行间距
                        paragraphPage.setSpacingBefore(60f); //设置段落上空白
                        paragraphPage.setSpacingAfter(0f); //设置段落下空白
                        document.add(paragraphPage);

                        document.add(paragraphTitle);

                        firsttitle = new PdfPTable(3);
                        firsttitle.setTotalWidth(PageSize.A4.getWidth() - 68);
                        firsttitle.setWidths(new int[]{30, 40, 30});
                        firsttitle.setLockedWidth(true);
                        firsttitle.getDefaultCell().setFixedHeight(-10);
                        firsttitle.getDefaultCell().setBorder(Rectangle.NO_BORDER);
                        firsttitle.addCell(new Paragraph("", iTextPDFUtil.getColorFont(BaseColor.BLACK, 10, "宋体")));
                        firsttitle.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
                        firsttitle.addCell(new Paragraph(pzrq.substring(0, 4) + "年" + pzrq.substring(5, 7) + "月" + pzrq.substring(8, 10) + "日", iTextPDFUtil.getColorFont(BaseColor.BLACK, 10, "宋体")));
                        firsttitle.getDefaultCell().setHorizontalAlignment(Element.ALIGN_RIGHT);

                        firsttitle.addCell(new Paragraph("第" + ++count + "页，共" + total + "页", iTextPDFUtil.getColorFont(BaseColor.BLACK, 10, "宋体")));
                        firsttitle.setSpacingAfter(20f); //设置段落下空白
                        document.add(firsttitle);

                        document.add(subtitle);
                        table2.setSpacingBefore(8f);//表格前间距
                        for (String col : headNames) {
                            table2.addCell(createCellNoHeight(col, headfont, Element.ALIGN_CENTER));
                        }
                        index = 0;
                    }
                    table2.addCell(createCell(rowData.getFlxh().toString(), textfont));
                    table2.addCell(createCellAutoSize(rowData.getZy(), Element.ALIGN_LEFT));
                    table2.addCell(createCellAutoSize(rowData.getKjkm(), Element.ALIGN_LEFT));
                    String j = StringUtil.fmtMicrometer(BigDecimalUtil.getData(rowData.getJ()).toString());
                    String d = StringUtil.fmtMicrometer(BigDecimalUtil.getData(rowData.getD()).toString());
                    table2.addCell(createCell("0".equals(j) ? "" : j, textfont, Element.ALIGN_RIGHT));
                    table2.addCell(createCell("0".equals(d) ? "" : d, textfont, Element.ALIGN_RIGHT));
                    index++;
                }

                //尾页不足14行补齐
                while (index < 14) {
                    table2.addCell(createCell("", textfont));
                    table2.addCell(createCell("", textfont, Element.ALIGN_LEFT));
                    table2.addCell(createCell("", textfont, Element.ALIGN_LEFT));
                    table2.addCell(createCell("", textfont, Element.ALIGN_RIGHT));
                    table2.addCell(createCell("", textfont, Element.ALIGN_RIGHT));
                    index++;
                }
                document.add(table2);

                //底部合计
                PdfPTable table3 = new PdfPTable(new float[]{500, 80, 80});
                table3.setTotalWidth(maxWidth);
                table3.setLockedWidth(true);
                table3.setHorizontalAlignment(Element.ALIGN_CENTER);
                table3.getDefaultCell().setBorder(1);

                table3.addCell(createCell("合计：人民币" + item.getTotal1(), totalfont));
                table3.addCell(createCell(BigDecimalUtil.getData(item.getTotal2()).toString(), textfont));
                table3.addCell(createCell(BigDecimalUtil.getData(item.getTotal2()).toString(), textfont));

                document.add(table3);


                PdfPTable footertitle = new PdfPTable(4);
                footertitle.setTotalWidth(PageSize.A4.getWidth() - 68);
                footertitle.setWidths(new int[]{33, 33, 33, 33});
                footertitle.setLockedWidth(true);
                footertitle.getDefaultCell().setFixedHeight(-10);
                footertitle.getDefaultCell().setBorder(Rectangle.NO_BORDER);
                footertitle.addCell(new Paragraph("财务主管：" + item.getCwzg(), iTextPDFUtil.getColorFont(BaseColor.BLACK, 10, "宋体")));
                footertitle.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
                footertitle.addCell(new Paragraph("审核员：" + ((StringUtil.isEmpty(item.getShy()) || item.getShy().equals("null")) ? "" : item.getShy()), iTextPDFUtil.getColorFont(BaseColor.BLACK, 10, "宋体")));
                footertitle.addCell(new Paragraph("记账员：" + ((StringUtil.isEmpty(item.getJzy()) || item.getJzy().equals("null")) ? "" : item.getJzy()), iTextPDFUtil.getColorFont(BaseColor.BLACK, 10, "宋体")));
                footertitle.getDefaultCell().setHorizontalAlignment(Element.ALIGN_RIGHT);
                footertitle.addCell(new Paragraph("制单员：" + item.getZdy(), iTextPDFUtil.getColorFont(BaseColor.BLACK, 10, "宋体")));
                document.add(footertitle);

                document.newPage();
            }
        }


    }

/**------------------------创建表格单元格的方法start----------------------------*/
    /**
     * 创建单元格(指定字体)
     *
     * @param value
     * @param font
     * @return
     */
    public PdfPCell createCell(String value, Font font) {
        PdfPCell cell = new PdfPCell();
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell.setPhrase(new Phrase(value, font));
        cell.setPaddingBottom(5f);
        cell.setPaddingTop(5f);
        cell.setFixedHeight(38);
        return cell;
    }

    /**
     * 创建单元格（指定字体、水平..）
     *
     * @param value
     * @param font
     * @param align
     * @return
     */
    public PdfPCell createCell(String value, Font font, int align) {
        PdfPCell cell = new PdfPCell();
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell.setHorizontalAlignment(align);
        cell.setPhrase(new Phrase(value, font));
        cell.setPaddingBottom(5f);
        cell.setPaddingTop(5f);
        cell.setFixedHeight(38);
        return cell;
    }


    /**
     * 创建单元格（指定字体、水平..）
     *
     * @param value
     * @param font
     * @param align
     * @return
     */
    public PdfPCell createCellNoHeight(String value, Font font, int align) {
        PdfPCell cell = new PdfPCell();
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell.setHorizontalAlignment(align);
        cell.setPhrase(new Phrase(value, font));
        cell.setPaddingBottom(5f);
        cell.setPaddingTop(5f);
        return cell;
    }

    /**
     * 创建单元格（指定字体、水平..）
     *
     * @param value
     * @param align
     * @return
     */
    public PdfPCell createCellAutoSize(String value, int align) {
        PdfPCell cell = new PdfPCell();
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell.setHorizontalAlignment(align);
        cell.setPhrase(new Phrase(value, checkValueWidth(value)));
        cell.setPaddingBottom(3f);
        cell.setPaddingTop(2f);
        cell.setFixedHeight(20);
        return cell;
    }

    /**
     * 创建单元格（指定字体、水平居..、单元格跨x列合并）
     *
     * @param value
     * @param font
     * @param align
     * @param colspan
     * @return
     */
    public PdfPCell createCell(String value, Font font, int align, int colspan) {
        PdfPCell cell = new PdfPCell();
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell.setHorizontalAlignment(align);
        cell.setColspan(colspan);
        cell.setPhrase(new Phrase(value, font));
        return cell;
    }

    /**
     * 创建单元格（指定字体、水平居..、单元格跨x列合并、设置单元格内边距）
     *
     * @param value
     * @param font
     * @param align
     * @param colspan
     * @param boderFlag
     * @return
     */
    public PdfPCell createCell(String value, Font font, int align, int colspan, boolean boderFlag) {
        PdfPCell cell = new PdfPCell();
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell.setHorizontalAlignment(align);
        cell.setColspan(colspan);
        cell.setPhrase(new Phrase(value, font));
        cell.setPadding(3.0f);
        if (!boderFlag) {
            cell.setBorder(0);
            cell.setPaddingTop(15.0f);
            cell.setPaddingBottom(8.0f);
        } else if (boderFlag) {
            cell.setBorder(0);
            cell.setPaddingTop(0.0f);
            cell.setPaddingBottom(15.0f);
        }
        return cell;
    }

    /**
     * 创建单元格（指定字体、水平..、边框宽度：0表示无边框、内边距）
     *
     * @param value
     * @param font
     * @param align
     * @param borderWidth
     * @param paddingSize
     * @param flag
     * @return
     */
    public PdfPCell createCell(String value, Font font, int align, float[] borderWidth, float[] paddingSize, boolean flag) {
        PdfPCell cell = new PdfPCell();
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell.setHorizontalAlignment(align);
        cell.setPhrase(new Phrase(value, font));
        cell.setBorderWidthLeft(borderWidth[0]);
        cell.setBorderWidthRight(borderWidth[1]);
        cell.setBorderWidthTop(borderWidth[2]);
        cell.setBorderWidthBottom(borderWidth[3]);
        cell.setPaddingTop(paddingSize[0]);
        cell.setPaddingBottom(paddingSize[1]);
        if (flag) {
            cell.setColspan(2);
        }
        return cell;
    }
/**------------------------创建表格单元格的方法end----------------------------*/


/**--------------------------创建表格的方法start------------------- ---------*/
    /**
     * 创建默认列宽，指定列数、水平(居中、右、左)的表格
     *
     * @param colNumber
     * @param align
     * @return
     */
    public PdfPTable createTable(int colNumber, int align) {
        PdfPTable table = new PdfPTable(colNumber);
        try {
            table.setTotalWidth(maxWidth);
            table.setLockedWidth(true);
            table.setHorizontalAlignment(align);
            table.getDefaultCell().setBorder(1);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return table;
    }

    /**
     * 创建指定列宽、列数的表格
     *
     * @param widths
     * @return
     */
    public PdfPTable createTable(float[] widths) {
        PdfPTable table = new PdfPTable(widths);
        try {
            table.setTotalWidth(maxWidth);
            table.setLockedWidth(true);
            table.setHorizontalAlignment(Element.ALIGN_CENTER);
            table.getDefaultCell().setBorder(1);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return table;
    }

    /**
     * 创建空白的表格
     *
     * @return
     */
    public PdfPTable createBlankTable() {
        PdfPTable table = new PdfPTable(1);
        table.getDefaultCell().setBorder(0);
        table.addCell(createCell("", keyfont));
        table.setSpacingAfter(20.0f);
        table.setSpacingBefore(20.0f);
        return table;
    }

    /**
     * --------------------------创建表格的方法end------------------- ---------
     */

    public Font checkValueWidth(String value) {
        Font font = textfont;
        if (StringUtil.isNotEmpty(value)) {
            float width = bfChinese.getWidthPoint(value, 10);
            if (width / 120 >= 1 && value.length() < 50) {
                font = text1font;
            } else if (width / 120 >= 1 && value.length() < 75) {
                font = text2font;
            } else if (width / 120 >= 1 && value.length() < 100) {
                font = text3font;
            } else if (width / 120 >= 1 && value.length() < 125) {
                font = text4font;
            } else if (width / 120 >= 2 && value.length() < 150) {
                font = text5font;
            } else if (width / 120 >= 2 && value.length() >= 200) {
                font = text6font;
            }
        }
        return font;
    }

}
